<template>
    <div class="chat-container">
      <!-- 左侧会话列表 -->
      <div class="conversation-list">
        <div class="list-header">
          <h3>聊天</h3>
          <el-input
            v-model="searchText"
            placeholder="搜索"
            prefix-icon="el-icon-search"
            clearable
          />
        </div>
        
        <div class="conversation-items">
          <div
            v-for="conv in filteredConversations"
            :key="conv.id"
            class="conversation-item"
            :class="{ active: activeConversation?.id === conv.id }"
            @click="selectConversation(conv)"
          >
            <el-avatar :size="48" :src="conv.partner_avatar" />
            <div class="conversation-info">
              <div class="conversation-top">
                <span class="partner-name">{{ conv.partner_name }}</span>
                <span class="conversation-time">{{ formatTime(conv.updatedat) }}</span>
              </div>
              <div class="conversation-bottom">
                <p class="last-message">
                  <template v-if="conv.lastmessagetype === 'text'">
                    {{ conv.lastmessagecontent }}
                  </template>
                  <template v-else-if="conv.lastmessagetype === 'image'">
                    [图片]
                  </template>
                  <template v-else-if="conv.lastmessagetype === 'voice'">
                    [语音]
                  </template>
                </p>
                <el-badge 
                  :value="conv.unread_count" 
                  :max="99" 
                  v-if="conv.unread_count > 0" 
                  class="unread-badge"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 右侧聊天区域 -->
      <div class="chat-area" v-if="activeConversation">
        <div class="chat-header">
          <el-avatar :size="40" :src="activeConversation.partner_avatar" />
          <span class="partner-name">{{ activeConversation.partner_name }}</span>
        </div>
        
        <div class="message-list" ref="messageList">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message-item"
            :class="{ 'my-message': message.senderid === currentUser.id }"
          >
            <el-avatar
              v-if="message.senderid !== currentUser.id"
              :size="36"
              :src="activeConversation.partner_avatar"
              class="message-avatar"
            />
            
            <div class="message-content">
              <div v-if="message.type === 'text'" class="message-text">
                {{ message.content }}
                <el-icon 
                  v-if="message.senderid === currentUser.id && message.canRecall"
                  class="recall-icon"
                  @click="recallMessage(message)"
                >
                  <Close />
                </el-icon>
              </div>
              <img
                v-else-if="message.type === 'image'"
                :src="message.content"
                alt="图片"
                class="message-image"
              />
              <div
                v-else-if="message.type === 'voice'"
                class="message-voice"
                @click="playVoice(message)"
              >
                <el-icon><Microphone /></el-icon>
                <span>语音消息</span>
              </div>
              
              <div class="message-time">
                {{ formatTime(message.createdat) }}
                <span v-if="message.status === 'sent'">
                  <el-icon><Check /></el-icon>
                </span>
                <span v-else-if="message.status === 'read'">
                  <el-icon><Check /></el-icon>
                </span>
              </div>
            </div>
            
            <el-avatar
              v-if="message.senderid === currentUser.id"
              :size="36"
              :src="currentUser.avatar"
              class="message-avatar"
            />
          </div>
        </div>
        
        <div class="message-input-area">
<!-- 输入框 -->
         <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            resize="none"
            @keyup.enter="sendMessage"
          />

          <!-- 工具栏 -->
          <div class="toolbar">
            <el-icon class="tool-icon" @click="showEmojiPicker = !showEmojiPicker">
              <HelpFilled />
            </el-icon>
            <el-icon class="tool-icon" @click="openImagePicker">
              <Picture />
            </el-icon>
            <el-icon class="tool-icon" @click="startVoiceRecording">
              <Microphone />
            </el-icon>
            <input
              type="file"
              ref="imageInput"
              accept="image/*"
              style="display: none"
              @change="handleImageUpload"
            />
          </div>
          
          <!-- 表情选择器 -->
          <div class="emoji-picker" v-if="showEmojiPicker">
            <span
              v-for="emoji in emojis"
              :key="emoji"
              @click="insertEmoji(emoji)"
            >
              {{ emoji }}
            </span>
          </div>
          
          
          
          <!-- 发送按钮 -->
          <div class="send-button">
            <el-button
              type="primary"
              :disabled="!newMessage.trim()"
              @click="sendMessage"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 无会话选中时的提示 -->
      <div class="empty-chat" v-else>
        <div class="empty-content">
          <el-icon class="empty-icon"><ChatDotRound /></el-icon>
          <p>请从左侧选择聊天会话</p>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, nextTick, watch, onUnmounted  } from 'vue'
  import { Check, Close, Microphone, Picture, HelpFilled, ChatDotRound } from '@element-plus/icons-vue'
  import request from '../utils/request'
  import { useUserStore } from '../utils/userStore'
  
  const userStore = useUserStore()
  const currentUser = userStore.user
  
  // 会话列表相关
  const conversations = ref([])
  const searchText = ref('')
  const activeConversation = ref(null)
  const messageList = ref(null)
  
  // 消息相关
  const messages = ref([])
  const newMessage = ref('')
  const showEmojiPicker = ref(false)
  const imageInput = ref(null)

    // 定义一个定时器变量
let chatRefreshTimer = null;
let conversationRefreshTimer = null; // 新增一个变量用于保存会话列表刷新定时器

  // 选择会话
const selectConversation = async (conversation) => {
  
  
  activeConversation.value = conversation
  await fetchMessages(conversation)
  // 清除之前的定时器
  if (chatRefreshTimer) {
    clearInterval(chatRefreshTimer)
  }
  // 设置新的定时器
  chatRefreshTimer = setInterval(() => {
    fetchMessages(conversation)
  }, 5000)
}


  // 表情列表
  const emojis = ['😀', '😂', '😍', '👍', '❤️', '🙏', '😊', '😎', '😢', '😡']
  
  // 获取会话列表
  const fetchConversations = async () => {
    try {
      const response = await request.post('/xhs/conversations/getConversations', {
        userid: currentUser.id
      })
      
      conversations.value = response.data.data
    } catch (error) {
      console.error('获取会话列表失败:', error)
    }
  }
  
  // 获取聊天消息
  const fetchMessages = async (conversation) => {
    try {
      
      const response = await request.post('/xhs/messages/getMessages', {
        // senderid: conversationId,
        // receiverid: currentUser.id
        senderid: conversation.user1id,
        receiverid: conversation.user2id
      })

      
      if (activeConversation.value && activeConversation.value.id === conversation.id) {
      messages.value = response.data.data
      scrollToBottom()
    }
      // 标记消息为已读
      //await markMessagesAsRead(conversationId)
      // 滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    } catch (error) {
      console.error('获取消息失败:', error)
    }
  }
  
  // 标记消息为已读
  const markMessagesAsRead = async (conversationId) => {
    try {
      await request.post('/xhs/messages/markAsRead', {
        senderid: conversationId,
        userid: currentUser.id
      })
      // 更新会话未读数
      const conv = conversations.value.find(c => c.id === conversationId)
      if (conv) {
        conv.unread_count = 0
      }
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 发送消息
  const sendMessage = async () => {
    if (!newMessage.value.trim() || !activeConversation.value) return
    
    try {
      const messageData = {
        senderid: currentUser.id,
        //接收着跟当前用户不一样
        receiverid: activeConversation.value.user1id === currentUser.id ? activeConversation.value.user2id : activeConversation.value.user1id,
        content: newMessage.value,
        type: 'text'
      }
      
      const response = await request.post('/xhs/messages/sendMessage', messageData)
      
      if (!Array.isArray(messages.value)) {
        messages.value = []
    }

      // 添加到本地消息列表
      messages.value.push({
        ...messageData,
        id: response.data.data.id,
        createdat: new Date().toISOString(),
        status: 'sent',
        canRecall: true
      })
      
      // 更新会话列表最后一条消息
      updateConversationLastMessage(activeConversation.value.id, {
        content: newMessage.value,
        type: 'text',
        createdat: new Date().toISOString()
      })
      
      newMessage.value = ''
      showEmojiPicker.value = false
      scrollToBottom()
      
      // 设置2分钟内可撤回
      setTimeout(() => {
        const msg = messages.value.find(m => m.id === response.data.id)
        if (msg) {
          msg.canRecall = false
        }
      }, 120000)
      
    } catch (error) {
      console.error('发送消息失败:', error)
    }
  }
  
  // 撤回消息
  const recallMessage = async (message) => {
    try {
      await request.post('/xhs/messages/recall', {
        message_id: message.id,
        userid: currentUser.id
      })
      
      // 更新本地消息
      const index = messages.value.findIndex(m => m.id === message.id)
      if (index !== -1) {
        messages.value[index].content = '消息已撤回'
        messages.value[index].type = 'system'
        messages.value[index].canRecall = false
      }
      
      // 更新会话最后一条消息
      if (index === messages.value.length - 1) {
        updateConversationLastMessage(activeConversation.value.id, {
          content: '消息已撤回',
          type: 'system',
          createdat: new Date().toISOString()
        })
      }
      
    } catch (error) {
      console.error('撤回消息失败:', error)
      ElMessage.error('撤回消息失败: ' + error.message)
    }
  }
  

  
  // 更新会话最后一条消息
const updateConversationLastMessage = (conversationId, message) => {
  const convIndex = conversations.value.findIndex(c => c.id === conversationId)
  if (convIndex !== -1) {
    const updatedConv = {
      ...conversations.value[convIndex],
      last_message_content: message.content,
      last_message_type: message.type,
      updatedat: new Date().toISOString()
    }
    
    // 更新并重新排序
    conversations.value.splice(convIndex, 1, updatedConv)
    conversations.value.sort((a, b) => new Date(b.updatedat) - new Date(a.updatedat))
  }
}
  
  // 滚动到底部
  const scrollToBottom = () => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  }
  
  // 打开图片选择器
  const openImagePicker = () => {
    imageInput.value.click()
  }
  
  // 处理图片上传
  const handleImageUpload = async (event) => {
    const file = event.target.files[0]
    if (!file || !activeConversation.value) return
    
    try {
      const formData = new FormData()
      formData.append('image', file)
      formData.append('senderid', currentUser.id)
      formData.append('receiverid', activeConversation.value.user1id === currentUser.id ? activeConversation.value.user2id : activeConversation.value.user1id)
      formData.append('type', 'image')
      debugger;

      const response = await request.post('/xhs/messages/sendMessageImage', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      debugger;
      // 添加到本地消息列表
      messages.value.push({
        id: response.data.data.id,
        senderid: activeConversation.value.id,
        senderid: currentUser.id,
        receiverid: activeConversation.value.partner_id,
        content: response.data.url,
        type: 'image',
        createdat: new Date().toISOString(),
        status: 'sent',
        canRecall: true
      })
      
      // 更新会话列表最后一条消息
      updateConversationLastMessage(activeConversation.value.id, {
        content: '[图片]',
        type: 'image',
        createdat: new Date().toISOString()
      })
      
      scrollToBottom()
      
      // 重置文件输入
      event.target.value = ''
      
      // 设置2分钟内可撤回
      setTimeout(() => {
        const msg = messages.value.find(m => m.id === response.data.id)
        if (msg) {
          msg.canRecall = false
        }
      }, 120000)
      
    } catch (error) {
      console.error('图片上传失败:', error)
      ElMessage.error('图片上传失败')
    }
  }
  
  // 插入表情
  const insertEmoji = (emoji) => {
    newMessage.value += emoji
  }
  
  // 开始语音录制
  const startVoiceRecording = () => {
    ElMessage.info('语音功能正在开发中')
  }
  
  // 播放语音
  const playVoice = (message) => {
    console.log('播放语音:', message)
  }
  
  // 格式化时间
  const formatTime = (time) => {
    const date = new Date(time)
    const now = new Date()
    
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    } else if (date.getFullYear() === now.getFullYear()) {
      return date.toLocaleDateString([], { month: 'short', day: 'numeric' })
    } else {
      return date.toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' })
    }
  }
  
  // 过滤会话列表
  const filteredConversations = computed(() => {
    
    if (!searchText.value) {
      return conversations.value
    }
    return conversations.value.filter(conv => 
      conv.partner_name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      conv.last_message_content?.toLowerCase().includes(searchText.value.toLowerCase())
    )
  })
  
  //初始化
  onMounted(() => {
    fetchConversations()
    // 定时刷新会话列表，并保存定时器引用
    conversationRefreshTimer = setInterval(fetchConversations, 10000)
  })

  // 在组件卸载时清除定时器
onUnmounted(() => {
  if (chatRefreshTimer) {
    clearInterval(chatRefreshTimer)
  };

   // 清除会话列表刷新定时器
   if (conversationRefreshTimer) {
    clearInterval(conversationRefreshTimer)
  }
 
})
  
  // 监听活动会话变化
//   watch(activeConversation, (newVal) => {
//     if (newVal) {
//       // 设置定时刷新消息
//       const intervalId = setInterval(() => {
//         if (activeConversation.value?.id === newVal.id) {
//           fetchMessages(newVal.id)
//         } else {
//           clearInterval(intervalId)
//         }
//       }, 5000)
//     }
//   })
  </script>
  
  <style scoped>
  /* 全局样式 */
.chat-container {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  height: 88vh;
  display: flex;
  background-color: #f8f8f8;
}

/* 会话列表样式 */
.conversation-list {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  box-shadow: 1px 0 4px rgba(0, 0, 0, 0.05);
}

.list-header {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.search-input {
  margin-top: 12px;
  border-radius: 18px;
  background-color: #f5f5f5;
  border: none;
  padding: 8px 15px;
}

.search-input :deep(.el-input__inner) {
  background-color: #f5f5f5;
  border: none;
  height: 36px;
  line-height: 36px;
}

.search-input :deep(.el-input__prefix) {
  display: flex;
  align-items: center;
  padding-left: 8px;
}

.conversation-items {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 10px;
}

.conversation-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.conversation-item:hover {
  background-color: #f9f9f9;
}

.conversation-item.active {
  background-color: #f0f7ff;
}

.conversation-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #ff2442;
}

.conversation-avatar {
  flex-shrink: 0;
}

.conversation-info {
  flex: 1;
  margin-left: 12px;
  overflow: hidden;
}

.conversation-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.partner-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.conversation-time {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.conversation-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  margin: 0;
  font-size: 13px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.unread-badge {
  margin-left: 8px;
}

.unread-badge :deep(.el-badge__content) {
  background-color: #ff2442;
  border: none;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  font-size: 11px;
}

/* 聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.empty-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.empty-content {
  text-align: center;
  color: #999;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #ddd;
}

.empty-content p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.chat-header {
  padding: 12px 6px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.chat-header .partner-name {
  margin-left: 10px;
  font-size: 16px;
  font-weight: 500;
}

.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f8f8f8;
  background-image: url('');
  background-size: 40px 40px;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message-item.my-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
  position: relative;
}

.message-text {
  padding: 10px 14px;
  background-color: #fff;
  border-radius: 18px;
  word-break: break-word;
  font-size: 15px;
  line-height: 1.5;
  color: #333;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
}

.my-message .message-text {
  background-color: #0cc206;
  color: #fff;
}

.recall-icon {
  position: absolute;
  right: -20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
  color: #999;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-item:hover .recall-icon {
  opacity: 1;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.message-image:hover {
  transform: scale(1.02);
}

.message-voice {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  background-color: #fff;
  border-radius: 18px;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message-voice .el-icon {
  margin-right: 8px;
  color: #ff2442;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-time .el-icon {
  margin-left: 4px;
  font-size: 12px;
}

.my-message .message-time .el-icon {
  color: #ff2442;
}

/* 消息输入区域样式 */
.message-input-area {
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
}

.toolbar {
  display: flex;
  padding-bottom: 8px;
}

.tool-icon {
  font-size: 20px;
  color: #666;
  margin-right: 16px;
  cursor: pointer;
  transition: color 0.2s;
}

.tool-icon:hover {
  color: #ff2442;
}

.emoji-picker {
  display: flex;
  flex-wrap: wrap;
  padding: 8px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.emoji-picker span {
  font-size: 24px;
  padding: 6px;
  cursor: pointer;
  transition: transform 0.2s;
}

.emoji-picker span:hover {
  transform: scale(1.2);
}

.message-textarea {
  margin-bottom: 8px;
}

.message-textarea :deep(.el-textarea__inner) {
  border: none;
  background-color: #f5f5f5;
  border-radius: 18px;
  padding: 12px 16px;
  font-size: 15px;
  line-height: 1.5;
  resize: none;
  box-shadow: none;
}

.message-textarea :deep(.el-textarea__inner):focus {
  background-color: #f0f0f0;
}

.send-button {
  text-align: right;
}

.send-button .el-button {
  border-radius: 18px;
  padding: 8px 20px;
  background-color: #ff2442;
  border: none;
}

.send-button .el-button:hover {
  background-color: #ff4757;
}

.send-button .el-button:disabled {
  background-color: #f5f5f5;
  color: #ccc;
}

/* 小红点样式 */
.unread-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #ff2442;
  border-radius: 50%;
  margin-left: 4px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
  }
  
  .conversation-list {
    width: 100%;
    height: 40vh;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .chat-area {
    height: 60vh;
  }
}
  </style>